/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Gerente.Gerenciar;

import Controle.Controlador;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Andre Luiz
 */
public class GerenciarSabor extends javax.swing.JFrame {
    ArrayList<ArrayList<String>> sabores;
    DefaultTableModel modelo;
    TableRowSorter sorter;
    /**
     * Creates new form GerenciarSabor
     */
    public GerenciarSabor() {
        initComponents();
        modelo = (DefaultTableModel) jtSabores.getModel();
        sorter = new TableRowSorter(modelo);
        jScrollPane1. getViewport().setBackground(Color.WHITE);
        jtSabores.getColumnModel().getColumn(0).setMinWidth(0);
        jtSabores.getColumnModel().getColumn(0).setMaxWidth(0);
        jtSabores.getColumnModel().getColumn(3).setMinWidth(0);
        jtSabores.getColumnModel().getColumn(3).setMaxWidth(0);
        jtSabores.getColumnModel().getColumn(1).setPreferredWidth(100);
        jtSabores.getColumnModel().getColumn(2).setPreferredWidth(200);
        jtSabores.getColumnModel().getColumn(3).setPreferredWidth(70);
        sabores=imprimeDadosTabelas(carregarDadosBD());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtSabores = new javax.swing.JTable();
        jbInserirSabor = new javax.swing.JButton();
        jbEditarSabor = new javax.swing.JButton();
        jbRemoverSabor = new javax.swing.JButton();
        jtfFiltro = new javax.swing.JTextField();
        jlFiltro = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Gerenciar Saboress");

        jtSabores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Sabor", "Ingredientes", "Cod Categoria", "Categoria"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtSabores);

        jbInserirSabor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/InserirSabor.png"))); // NOI18N
        jbInserirSabor.setToolTipText("Inserir um novo Sabor");
        jbInserirSabor.setPreferredSize(new java.awt.Dimension(70, 66));
        jbInserirSabor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbInserirSaborActionPerformed(evt);
            }
        });

        jbEditarSabor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/EditarSabor.png"))); // NOI18N
        jbEditarSabor.setToolTipText("Editar Sabor");
        jbEditarSabor.setPreferredSize(new java.awt.Dimension(70, 64));
        jbEditarSabor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEditarSaborActionPerformed(evt);
            }
        });

        jbRemoverSabor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/delSabor.png"))); // NOI18N
        jbRemoverSabor.setToolTipText("Remover Sabor");
        jbRemoverSabor.setPreferredSize(new java.awt.Dimension(70, 64));
        jbRemoverSabor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbRemoverSaborActionPerformed(evt);
            }
        });

        jtfFiltro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jtfFiltroKeyReleased(evt);
            }
        });

        jlFiltro.setText("Filtro:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jlFiltro)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtfFiltro))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbEditarSabor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbInserirSabor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbRemoverSabor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtfFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlFiltro)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(80, 80, 80)
                        .addComponent(jbInserirSabor, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbEditarSabor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbRemoverSabor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 89, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void jbInserirSaborActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbInserirSaborActionPerformed
        // Ao clicar no botão Inserir Sabor
        new InserirAlterarSabor(this).setVisible(true);
    }//GEN-LAST:event_jbInserirSaborActionPerformed

    private void jtfFiltroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfFiltroKeyReleased
        // Filtro:
        sorter.setRowFilter(RowFilter.regexFilter(jtfFiltro.getText().toUpperCase(),1));
        jtSabores.setRowSorter(sorter);
    }//GEN-LAST:event_jtfFiltroKeyReleased

    private void jbEditarSaborActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEditarSaborActionPerformed
       //Editar Sabor
       try {
            int linha = jtSabores.getSelectedRow();
            if (linha != -1) {
                int codigo = Integer.parseInt(jtSabores.getValueAt(linha, 0).toString());
                InserirAlterarSabor inserir = new InserirAlterarSabor(this, codigo);
                inserir.setVisible(true);
                
            } else {
                throw new Exception("Selecione a linha do Sabor desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jbEditarSaborActionPerformed

    private void jbRemoverSaborActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRemoverSaborActionPerformed
       // Remover Sabor
       try {
            int linha = jtSabores.getSelectedRow();
            if (linha != -1) {
                int codigo = Integer.parseInt(jtSabores.getValueAt(linha, 0).toString());
                int aux = JOptionPane.showConfirmDialog(this, "Deseja realmente remover o Sabor Selecionado? ", "Remover Sabor", 1,3);
                if(aux==0){
                    Controlador.remover_Sabor(codigo);
                    atualizaTabela();
                }
                
            } else {
                throw new Exception("Selecione a linha do Sabor desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jbRemoverSaborActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbEditarSabor;
    private javax.swing.JButton jbInserirSabor;
    private javax.swing.JButton jbRemoverSabor;
    private javax.swing.JLabel jlFiltro;
    private javax.swing.JTable jtSabores;
    private javax.swing.JTextField jtfFiltro;
    // End of variables declaration//GEN-END:variables
    
    /**
     * Carrega todos os sabores do banco de dados
     * @return Retorna uma lista de Sabores 
     */
    private ArrayList<ArrayList<String>> carregarDadosBD(){
        return Controlador.carregarDadosBD_Sabores();
    }
    
    private ArrayList<ArrayList<String>> imprimeDadosTabelas(ArrayList<ArrayList<String>> sabores) {
        // Adiciona uma nova linha em branco no modelo  
        int linhaTabela = 0;
        jtSabores.setRowSorter(null); // desabilita o filtro
        
        for (int i = 0; i < sabores.size(); i++) {
            try{
                if (jtSabores.getRowCount() <= linhaTabela) {
                    modelo.addRow(new String[]{"", ""});
                }
                jtSabores.setValueAt(sabores.get(i).get(0), linhaTabela, 0);
                jtSabores.setValueAt(sabores.get(i).get(1), linhaTabela, 1);
                jtSabores.setValueAt(sabores.get(i).get(2), linhaTabela, 2);
                jtSabores.setValueAt(sabores.get(i).get(3), linhaTabela, 3);
                jtSabores.setValueAt(sabores.get(i).get(4), linhaTabela, 4);
            }catch(Exception ex){
                System.out.println("Erro ao imprimir os dados na tabela\n"+ex.getMessage());
            }

            linhaTabela++;
        }
        removeLinhasInutilizadas(linhaTabela);
        //reativa o filtro
        jtfFiltroKeyReleased(null);
        return sabores;
    }
    
    public void removeLinhasInutilizadas(int linhaTabela){
        for (int i = linhaTabela; i < jtSabores.getRowCount(); i++) {
            modelo.removeRow(i);
        }
    }
    
    public void atualizaTabela(){
        imprimeDadosTabelas(carregarDadosBD());
    } 
}
